<template>
  <view>
    <view>
      <image src="/static/bg.jpeg" class="responsive-images"></image>
    </view>
    <form class="form-container">
      <!-- 姓名(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">姓名</text>
        <input type="text" v-model="formData.name" placeholder="请输入姓名" />
      </view>
      <!-- 身份证号(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">身份证号</text>
        <input
          type="text"
          v-model="formData.idCard"
          placeholder="请输入身份证号"
        />
      </view>
      <!-- 手机号(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">手机号</text>
        <input
          type="text"
          v-model="formData.phone"
          placeholder="请输入手机号"
        />
      </view>

      <!-- 紧急联系人(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">紧急联系人</text>
        <input
          type="text"
          v-model="formData.emergencyContact"
          placeholder="请输入紧急联系人"
        />
      </view>

      <!-- 紧急联系电话(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">紧急联系电话</text>
        <input
          type="text"
          v-model="formData.emergencyPhone"
          placeholder="请输入紧急联系电话"
        />
      </view>

      <!-- 身体状况(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">身体状况</text>
        <!-- <input
          type="text"
          v-model="formData.healthCondition"
          placeholder="请输入身体状况"
        /> -->
        <picker
          v-model="formData.healthCondition"
          :range="healthConditionList.map((item) => item.name)"
          @change="onHealthChange"
        >
          <view>
            <!-- {{ formData.healthCondition }} -->
            {{ gethealthConditionName(formData.healthCondition) }}
          </view>
        </picker>
      </view>

      <!-- 籍贯(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">籍贯</text>
        <input
          type="text"
          v-model="formData.nativePlace"
          placeholder="请输入籍贯"
        />
      </view>

      <!-- 详细地址(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">详细地址</text>
        <input
          type="text"
          v-model="formData.address"
          placeholder="请输入详细地址"
        />
      </view>

      <!-- 所属项目(下拉框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">所属项目</text>
        <input
          type="text"
          v-model="formData.project"
          placeholder="请输入所属项目"
          disabled
        />
      </view>

      <!-- 详细地址(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">宿舍地址</text>
        <input
          type="text"
          v-model="formData.hostel_address"
          placeholder="请输入宿舍地址"
        />
      </view>

      <!-- 劳务公司(下拉框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">劳务公司</text>
        <picker
          v-model="formData.labor_company_id"
          :range="laborCompanyList.map((item) => item.name)"
          @change="onLaborCompanyChange"
        >
          <view>
            <!-- 通过计算属性获取劳务公司名称 -->
            {{ getLaborCompanyName(formData.labor_company_id) }}
          </view>
        </picker>
      </view>

      <!-- 工种(下拉框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">工种</text>
        <picker
          v-model="formData.job_type_id"
          :range="jobTypeList.map((item) => item.name)"
          @change="onJobTypeChange"
        >
          <view>{{ getJobTypeName(formData.job_type_id) }}</view>
        </picker>
      </view>

      <!-- 资格证书(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">资格证书</text>
        <input
          type="text"
          v-model="formData.certificate"
          placeholder="请输入资格证书"
        />
      </view>

      <!-- 车牌号(输入框) -->
      <view class="form-item inline-item gender-item">
        <text class="form-label">车牌号</text>
        <input
          type="text"
          v-model="formData.carLicense"
          placeholder="请输入车牌号"
        />
      </view>
      <button type="submit" @click="submitFormData" class="submit-button">
        提交
      </button>
    </form>

    <view class="popup-bg" v-if="showPopup" @click="closePopup"></view>
    <!-- 弹出层内容 -->
    <view class="popup-content" v-if="showPopup">
      <text>信息以录入，请点击签到</text>
      <view class="popup-buttons">
        <button class="cancel-button" @click="closePopup">取消</button>
        <button class="signin-button" @click="handleSignIn">签到</button>
      </view>
    </view>
  </view>
</template>

<script>
import {
  getProjectInfo,
  submitForm,
  getLaborCompanyList,
  getJobTypeList,
  getLoginInfo,
  getUserInfo,
} from "@/api/api.js";

export default {
  data() {
    return {
      projectAppId: "", // 从 URL 参数中获取的项目 APP ID
      projectInfo: null, // 项目信息
      projectId: "", // 项目 ID
      userInfo: null, // 用户信息
      userId: "", //用户ID
      showPopup: false, // 弹窗是否显示
      formData: {
        project_id: 0, // 项目ID
        user_id: 0, // 用户ID，默认1
        gender: 0, // 性别，默认男
        idCard: "",
        phone: "",
        emergencyContact: "",
        emergencyPhone: "",
        healthCondition: "",
        hostel_address: "",
        project: "",
        address: "",
        nativePlace: "",
        labor_company_id: 0,
        job_type_id: 0,
        certificate: "",
        carLicense: "",
      },
      laborCompanyList: [], // 示例劳务公司列表
      jobTypeList: [], // 示例工种列表
      healthConditionList: [
        { id: 1, name: "健康" },
        { id: 2, name: "有症状" },
        { id: 3, name: "无症状" },
        { id: 4, name: "残疾" },
        { id: 5, name: "其他" },
      ], // 示例身体状况列表
      rules: {
        name: {
          required: true,
          message: "姓名不能为空",
        },
        idCard: {
          required: true,
          message: "身份证号不能为空",
          pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
          messagePattern: "请输入正确的身份证号码",
        },
        phone: {
          required: true,
          message: "手机号不能为空",
          pattern: /^1[3-9]\d{9}$/,
          messagePattern: "请输入正确的手机号码",
        },
        emergencyContact: {
          required: true,
          message: "紧急联系人不能为空",
        },
        emergencyPhone: {
          required: true,
          message: "紧急联系电话不能为空",
          pattern: /^1[3-9]\d{9}$/,
          messagePattern: "请输入正确的手机号码",
        },
        hostel_address: {
          required: true,
          message: "宿舍地址不能为空",
        },
        address: {
          required: true,
          message: "详细地址不能为空",
        },
        nativePlace: {
          required: true,
          message: "籍贯不能为空",
        },
      },
    };
  },
  components: {},
  computed: {
    // 获取劳务公司名称的计算属性
    getLaborCompanyName() {
      return (id) => {
        const company = this.laborCompanyList.find((item) => item.id === id);
        return company ? company.name : "请选择劳务公司";
      };
    },
    getJobTypeName() {
      return (id) => {
        const jobType = this.jobTypeList.find((item) => item.id === id);
        return jobType ? jobType.name : "请选择工种";
      };
    },
    gethealthConditionName() {
      return (name) => {
        const healthCondition = this.healthConditionList.find(
          (item) => item.name === name
        );
        return healthCondition ? healthCondition.name : "请选择身体状况";
      };
    },
  },
  onLoad(options) {
    // 获取 URL 中的项目 ID
    if (options.projectId) {
      this.projectAppId = options.projectId;
      // 将 projectAppId 缓存到本地
      uni.setStorageSync("projectAppId", this.projectAppId);
    } else {
      this.projectAppId = uni.getStorageSync("projectAppId");
    }
    if (!this.projectAppId) {
      uni.showToast({ title: "参数错误", icon: "none" });
      return;
    }

    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get("code");
    console.log("window.location.search", window.location.search);
    console.log("code", code);
    if (code) {
      console.log("onLoadcode", code);
      this.getLoginInfo(code); // 微信登录

      return;
    } else {
      let userId = uni.getStorageSync("userId");
      console.log("userId", userId);
      if (!userId) {
        console.log("跳转到登录页面", userId);
        this.loginWithWeixin();
        // uni.navigateTo({
        //   url: `/pages/login/wx`,
        // });
      } else {
        this.userId = userId;
        this.formData.user_id = this.userId;
        this.getProjectInfo(); //获取项目信息
        this.getUserInfo(); //获取项目用户信息
        this.getlaborCompanyList();
        this.getjobTypeList();
      }
    }
  },
  methods: {
    loginWithWeixin() {
      const appId = "wx9f531b5e4d85c09f"; // 替换为你的微信开放平台网站应用 AppID  观和的appid
      const redirectUri = encodeURIComponent(
        `https://gdh6.aoejdm.top/#/?projectAppId=${this.projectAppId}`
      ); // 替换为你的授权回调域名及路径

      const scope = "snsapi_base"; // 授权作用域，可选 snsapi_base 或 snsapi_userinfo  snsapi_login
      const state = "STATE";
      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
      console.log("url", url);
      window.location.href = url;
    },
    // 检查登录状态
    async getLoginInfo(code) {
      try {
        const res = await getLoginInfo({
          code: code,
        });
        if (res.code === 1) {
          //微信登录成功，获取用户信息
          this.userInfo = res.data;
          this.userId = res.data.id;
          let userId = uni.getStorageSync("userId");
          if (userId) {
            this.userId = userId;
            this.formData.user_id = this.userId;
          } else {
            this.userId = res.data.id;
            this.formData.user_id = this.userId;

            uni.setStorageSync("token", res.data.auth);
            uni.setStorageSync("userId", res.data.id);
            uni.setStorageSync("userInfo", res.data);
          }
          this.getProjectInfo(); //获取项目信息
          this.getUserInfo(); //获取项目用户信息
          this.getlaborCompanyList();
          this.getjobTypeList();
        } else {
          uni.showToast({ title: "登录失败", icon: "none" });
        }
      } catch (err) {
        console.log("getLoginInfo", err);
        uni.showToast({ title: "网络请求失败..", icon: "none" });
      }
    },
    async getUserInfo() {
      console.log("获取用户信息", this.userId, this.projectId);
      if (!this.userId || !this.projectId) {
        uni.showToast({
          title: "userId或projectId为空." + this.userId + "." + this.projectId,
          icon: "none",
        });
      }
      try {
        const res = await getUserInfo({
          userId: this.userId,
          projectId: this.projectId,
        });

        console.log("用户信息", res.data);
        if (res.code === -12) {
          uni.navigateTo({
            url: `/pages/auth/auth?projectAppId=${this.projectAppId}&userId=${this.userId}&projectId=${this.projectId}`,
          });
        } else {
          this.formData.name = res.data.name;
          this.formData.gender = res.data.gender;
          this.formData.idCard = res.data.id_card;
          this.formData.phone = res.data.phone;
          this.formData.emergencyContact = res.data.emergencyContact;
          this.formData.emergencyPhone = res.data.emergencyPhone;
          this.formData.healthCondition = res.data.healthCondition;
          this.formData.nativePlace = res.data.nativePlace;
          this.formData.address = res.data.address;
          this.formData.hostel_address = res.data.hostel_address;
          this.formData.labor_company_id = res.data.labor_company_id;
          this.formData.job_type_id = res.data.job_type_id;
          this.formData.certificate = res.data.certificate;
          this.formData.carLicense = res.data.carLicense;
        }
      } catch (err) {
        uni.showToast({ title: "网络请求失败。", icon: "none" });
      }
    },
    async submitFormData() {
      for (let key in this.rules) {
        let rule = this.rules[key];
        if (rule.required && !this.formData[key]) {
          uni.showToast({
            title: rule.message,
            icon: "none",
          });
          return;
        }
        if (rule.pattern && !rule.pattern.test(this.formData[key])) {
          uni.showToast({
            title: rule.messagePattern,
            icon: "none",
          });
          return;
        }
      }
      console.log("formData", this.formData);
      console.log("user_id", this.userId);

      if (this.formData.user_id === 0) {
        uni.showToast({
          title: "请选择所属项目",
          icon: "none",
        });
        return;
      }
      try {
        const res = await submitForm(this.formData);
        if (res.code === 1) {
          uni.showToast({
            title: "提交成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: "提交失败!",
            icon: "none",
          });
        }
      } catch (err) {
        console.log("submitForm", err);
        uni.showToast({
          title: "网络请求失败!!!",
          icon: "none",
        });
      }
    },
    // 签到处理函数
    handleSignIn() {
      // 这里可以添加签到的具体逻辑，例如发送请求到后端记录签到信息
      uni.showToast({ title: "签到成功", icon: "success" });
      this.showPopup = false; // 关闭弹窗
    },
    onProjectChange(e) {
      this.formData.project = e.detail.value;
    },
    onLaborCompanyChange(e) {
      const selectedIndex = e.detail.value; // 获取选择的索引
      const selectedCompany = this.laborCompanyList[selectedIndex]; // 根据索引获取劳务公司对象
      if (selectedCompany) {
        this.formData.labor_company_id = selectedCompany.id; // 将劳务公司的 ID 赋值给 formData.laborCompany
        console.log("劳务公司ID", selectedCompany.id);
      }
    },
    onHealthChange(e) {
      const selectedIndex = e.detail.value; // 获取选择的索引
      const selectedCompany = this.healthConditionList[selectedIndex]; // 根据索引获取劳务公司对象
      if (selectedCompany) {
        this.formData.healthCondition = selectedCompany.name; // 将劳务公司的 ID 赋值给 formData.laborCompany
        // console.log("劳务公司ID", selectedCompany.id);
      }
    },
    onJobTypeChange(e) {
      const selectedIndex = e.detail.value; // 获取选择的索引
      const selectedCompany = this.jobTypeList[selectedIndex]; // 根据索引获取劳务公司对象
      if (selectedCompany) {
        this.formData.job_type_id = selectedCompany.id; // 将劳务公司的 ID 赋值给 formData.laborCompany
      }
    },
    onGenderChange(e) {
      this.formData.gender = e.detail.value;
    },
    //获取劳务公司列表
    async getlaborCompanyList() {
      try {
        const res = await getLaborCompanyList({ status: 1 });

        if (res.code === 1) {
          console.log("劳务公司列表", res.data);
          this.laborCompanyList = res.data;
        } else {
          uni.showToast({
            title: "获取劳务公司列表失败",
            icon: "none",
            duration: 3000,
          });
        }
      } catch (err) {
        uni.showToast({
          title: "网络请求失败!!",
          icon: "none",
          duration: 3000,
        });
      }
    },
    async getjobTypeList() {
      try {
        const res = await getJobTypeList({ status: 1 });
        if (res.code === 1) {
          this.jobTypeList = res.data;
        } else {
          uni.showToast({
            title: "获取工种列表失败",
            icon: "none",
            duration: 3000,
          });
        }
      } catch (err) {
        uni.showToast({ title: "网络请求失败", icon: "none", duration: 3000 });
      }
    },
    // 获取项目信息
    async getProjectInfo() {
      try {
        const res = await getProjectInfo({ appId: this.projectAppId });
        if (res.code === 1) {
          this.projectInfo = res.data;
          let projectId = uni.getStorageSync("projectId");
          if (projectId && projectId === res.data.id) {
            this.projectId = projectId;
          } else {
            this.projectId = res.data.id;
            if (this.projectId) {
              uni.setStorageSync("projectId", this.projectId);
            }
          }
          this.formData.project = res.data.app_name;
          this.formData.project_id = res.data.id;

          this.getUserInfo();
        } else {
          uni.showToast({
            title: "获取项目信息失败",
            icon: "none",
            duration: 3000,
          });
        }
      } catch (err) {
        console.log("getProjectInfo", err);
        uni.showToast({ title: "网络请求失败!", icon: "none", duration: 3000 });
      }
    },
    // 打开弹出层
    openPopup() {
      this.showPopup = true;
    },
    // 关闭弹出层
    closePopup() {
      this.showPopup = false;
    },
    // 签到处理函数
    handleSignIn() {
      // 这里可以添加签到的具体逻辑，例如发送请求到后端记录签到信息
      uni.showToast({ title: "签到成功", icon: "success" });
      this.showPopup = false; // 关闭弹窗
    },
  },
  onPullDownRefresh() {
    // 模拟异步请求数据
    setTimeout(() => {
      // 这里可以更新数据
      this.getProjectInfo(); //获取项目信息
      this.getUserInfo(); //获取项目用户信息
      this.getlaborCompanyList();
      this.getjobTypeList();
      // 停止下拉刷新动画
      uni.stopPullDownRefresh();
    }, 2000);
  },
};
</script>

<style scoped>
/* 图片响应式样式 */
.responsive-image {
  width: 100% !important;
  height: auto !important;
}

.form-container {
  /* margin-top: 30px; */
  /* padding: 20px; */
  border: 1px solid #ccc;
  /* border-radius: 5px; */
  background-color: #f9f9f9;
}

/* 表单项样式 */
.form-item {
  margin: 15px 10px 0 10px;
  padding-bottom: 3px;
  input {
    width: 100%;
  }
  picker {
    width: 100%;
  }
}

/* 表单标签样式 */
.form-label {
  display: block;
  margin-bottom: 0;
  margin-right: 10px;
  /* 添加固定宽度 */
  width: 100px;
}

/* 让 text 和 input 在一行内显示 */
.inline-item {
  display: flex;
  align-items: center;
}

.gender-item {
  border-bottom: 1px solid #cecece;
}

.radio-label {
  margin-right: 20px; /* 可以根据需要调整间距大小 */
}

/* 提交按钮样式 */
.submit-button {
  margin: 10px 120px 0 120px;
  /* padding: 10px 20px; */
  background-color: #007aff;
  color: white;
  border: none;
  border-radius: 5px;
}

.popup {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  z-index: 999;
}
.popup-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 浅灰色背景 */
  z-index: 998;
}

/* 弹出层内容 */
.popup-content {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  padding: 20px;
  z-index: 999;
  text {
    margin: 10px;
  }
}

/* 弹出层按钮容器 */
.popup-buttons {
  display: flex;
  justify-content: space-between;
}

.popup-buttons button {
  height: 40px;
  width: 80px;
  margin: 0 12px 0 12px;
  border: 2px none #ccc;
  /* padding: 10px 20px; */
  border-radius: 10px;
}

/* 取消按钮 */
.cancel-button {
  background-color: #fff;
  color: #000;
  border: 5px solid #000000;
}

/* 签到按钮 */
.signin-button {
  background-color: #007aff;
  color: #fff;
  border: none;
}

.responsive-images {
  width: 100%;
}
</style>
